package org.gzc.array;

import java.io.*;

/**
 * @Description:
 * @Author: guozongchao
 * @Date: 2020/8/1 13:21
 */
public class SparseArray {
    public static void main(String[] args) throws IOException, ClassNotFoundException {

        //原始二维数组
        int[][] chessArray = new int[11][11];
        chessArray[1][2] = 1;
        chessArray[2][3] = 2;
        chessArray[4][5] = 3;
        System.out.println("原始二维数组：");
        for (int[] row : chessArray) {
            for (int elem : row) {
                System.out.printf("%d\t", elem);
            }
            System.out.println();
        }

        System.out.println();

        //将二维数组转换成稀疏数组
        //先遍历二维数组，统计非零个数
        int sum = 0;
        for (int[] row : chessArray) {
            for (int elem : row) {
                if (elem != 0) {
                    sum++;
                }
            }
        }
        //创建稀疏数组，第一行存放原来二维数组的行数、列数、以及非零元素个数
        int[][] sparseArray = new int[sum + 1][3];
        sparseArray[0][0] = 11;
        sparseArray[0][1] = 11;
        sparseArray[0][2] = sum;
        //遍历二维数组，将非0元素加入到稀疏数组
        int count = 0;
        for (int i = 0; i < 11; i++) {
            for (int j = 0; j < 11; j++) {
                if (chessArray[i][j] != 0) {
                    count++;
                    sparseArray[count][0] = i;
                    sparseArray[count][1] = j;
                    sparseArray[count][2] = chessArray[i][j];
                }
            }
        }
        //遍历稀疏数组
        System.out.println("\n稀疏数组如下：");
        for (int[] row : sparseArray) {
            System.out.printf("%d\t%d\t%d\n", row[0], row[1], row[2]);
        }

        //保存稀疏数组到map.data文件中
        save(sparseArray,"map.data");

        System.out.println();

        //将稀疏数组还原为二维数组

        //从磁盘文件map.data中加载稀疏数组
        int[][] newSparseArray=load("map.data");

        int[][] newChessArray =new int[newSparseArray[0][0]][newSparseArray[0][1]];
        for (int i = 1; i <= sparseArray[0][2];i++) {
            newChessArray[sparseArray[i][0]][sparseArray[i][1]] = sparseArray[i][2];
        }
        //遍历新二维数组
        System.out.println("还原后的二维数组：");
        for (int[] row : newChessArray) {
            for (int elem : row) {
                System.out.printf("%d\t", elem);
            }
            System.out.println();
        }
    }

    //将稀疏数组写入本地文件保存
    public static void save(int[][] sparseArray,String fileName) throws IOException {
        ObjectOutputStream out=new ObjectOutputStream(new FileOutputStream(new File(fileName)));
        out.writeObject(sparseArray);
        out.flush();
        out.close();
    }

    //从文件中加载稀疏数组
    public static int[][] load(String fileName) throws IOException, ClassNotFoundException {
        ObjectInputStream in = new ObjectInputStream(new FileInputStream(fileName));
        int[][] object = (int[][])in.readObject();
        return object;
    }
}
